package com.xiaoyu.izf.controller;

import cn.hutool.crypto.SecureUtil;
import com.xiaoyu.izf.config.SysConfig;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, String userName, String pwd, String myCode) {
        if(StringUtils.isEmpty(userName)|| StringUtils.isEmpty(pwd)){
            return "<script>parent.callBack('用户名或密码不能为空。');</script>";
        }

        if(SysConfig.isNeedCheckCode==1){
            if(StringUtils.isEmpty(myCode)){
                return "<script>parent.callBack('请输入验证码。');</script>";
            }
            String codeSession = (String)request.getSession().getAttribute("BarPriRandCheckCode");
            if(codeSession!=null){
                codeSession=codeSession.toLowerCase();
            }else{
                return "<script>parent.callBack('验证码已过期。');</script>";
            }
            if(!myCode.toLowerCase().equals(codeSession)){
                return "<script>parent.callBack('验证码错误。');</script>";
            }
        }
        UserInfo admins = userInfoService.findByUserName(userName);
        if(admins!=null){
            pwd = SecureUtil.md5(pwd+ SysConfig.pwdEx);
            if(pwd.equals(admins.getPwd())){
                request.getSession().setAttribute(SysConfig.user_info_in_session_key, admins);
            }else {
                request.getSession(true).setAttribute("BarPriRandCheckCode", null);
                return "<script>parent.callBack('密码不正确。');</script>";
            }
        }else{
            request.getSession(true).setAttribute("BarPriRandCheckCode", null);
            return "<script>parent.callBack('用户不存在~！');</script>";
        }
        return "<script>parent.callBack('ok');</script>";
    }

    @RequestMapping("/logout")
    public String logOut(HttpServletRequest request) {
        request.getSession().setAttribute(SysConfig.user_info_in_session_key, null);
        return "redirect:/";
    }
}
